export function forEach(arr, cb){
    let variType = getVariType(arr);
    if(['array', 'object', 'domtokenlist', 'nodelist'].indexOf(variType) === -1){
        console.warn('foreach无法遍历非数组或对象类型');
        return;
    }
    if(getVariType(cb) !== 'function') return;

    if(variType === 'array'){
        for( let i = 0, l = arr.length; i < l; i++){
            let cbReturn = cb(arr[i], i, arr);
            if(getVariType(cbReturn) !== 'undefined' && !cbReturn) return;
        }
    }else{
        let keys = Object.keys(arr);
        for(let i = 0, l = keys.length; i < l; i++){
            let key = keys[i];
            let cbReturn = cb(arr[key], key, arr);
            if(getVariType(cbReturn) !== 'undefined' && !cbReturn) return;
        }
    }
}

export function each(list, cb, opts = {}){
    let start = opts.start || 0;
    let end = opts.end === undefined ? list.length - 1 : opts.end;
    if(getVariType(cb) !== 'function'){
        console.warn('回调函数不存在。');
        return;
    }

    for(let i = start; i <= end; i++){
        cb(list[i], i);
    }
}

export function isNil(vari){
    return vari === undefined || vari === null;
}

/**
 * 获取变量类型
 * @param {*} vari 
 * 
 * return: string | number | boolean | array | object | function | null | undefined | domtokenlist | nodelist
 */
export function getVariType(vari){
    return Object.prototype.toString.call(vari).toLowerCase().slice(8, -1);
}

export function isObject(vari){
    let type = getVariType(vari);
    return ['string', 'number', 'boolean', 'undefined', 'null'].indexOf(type) === -1;
}

export function deepClone(vari){
    return JSON.parse(JSON.stringify(vari));
}

export function addClass($el, className){
    let originClassList = $el.classList;
    let hasClass = false;
    forEach(originClassList, (name) => {
        if(name === className){
            hasClass = true;
            return false;
        }
    })
    if(!hasClass){
        $el.className = $el.className + ' ' + className;
    }
}

export function removeClass($el, className){
    let originClassName = $el.className;
    let reg = new RegExp(`(^|\\s)${className}($|\\s)`, 'g');
    let newClassName = originClassName.replace(reg, ' ');
    $el.className = newClassName;
}